import requests
from fake_useragent import UserAgent
from lxml import etree

UA = UserAgent().random
headers = {
    'User-Agent':UA
}
url ="https://movie.douban.com/top250"
res = requests.get(url,headers=headers)
res.encoding ='utf-8'

html = etree.HTML(res.text)  # 标签化
name = html.xpath('// div[@class="hd"] /a/span[1]/text()')
score = html.xpath('// div[@class="star"] /span[2]/text()')

zh = list(zip(name,score))
print(zh)
f= open('豆瓣电影.txt', 'wb')
for item in zh:
    f.write(b' '.join(str(x).encode() for x in item) + b'\n')
f.close()

# if len(name) == len(score) and all(name) and all(score):  # 确保两个列表长度相同且都0不为空
#     zh = list(zip(name, score))
#     # 使用循环来换行打印
#     for item in zh:
#         print(item[0], item[1])  # 或者使用print(f"{item[0]}: {item[1]}")
# else:
#     print("名字和分数的数量不匹配或列表为空")